package com.yc.entities;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yc.entities.custom.AppLoginPermissionBean;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LC
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="JwtUser对象", description="用户数据信息")
public class JwtUser implements UserDetails {

	private static final long serialVersionUID = 1L;

	@ApiModelProperty(value = "用户id")
	private final String id;
	@ApiModelProperty(value = "用户名")
	private final String username;
	@ApiModelProperty(value = "用户密码")
	private final String password;
	@ApiModelProperty(value = "用户权限信息")
	private final Collection<? extends GrantedAuthority> authorities;
	@ApiModelProperty(value = "是否启用")
	private final boolean enabled;
	@ApiModelProperty(value = "PC用户信息,扩展")
	private JSONArray pcCustomInfo;
	@ApiModelProperty(value = "PC用户,菜单栏科室对应,扩展")
	private JSONObject pcMenuDepartmentId;


	@ApiModelProperty(value = "app用户信息,扩展")
	private  List<AppLoginPermissionBean> appCustomInfo;
	public JwtUser(
			String id,
			String username,
			String password, List<String> authorities,
			boolean enabled
			) {
		this.id = id;
		this.username = username;
		this.password = password;
		this.authorities = mapToGrantedAuthorities(authorities);
		this.enabled = enabled;
	}

	public JwtUser(
			String id,
			String username,
			String password, String authorities,
			boolean enabled
			) {
		this.id = id;
		this.username = username;
		this.password = password;
		this.authorities = mapToGrantedAuthorities(authorities);
		this.enabled = enabled;
	}
	private List<GrantedAuthority> mapToGrantedAuthorities(List<String> authorities) {
        return authorities.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }
	private List<GrantedAuthority> mapToGrantedAuthorities(String authorities) {
        return Collections.singletonList(new SimpleGrantedAuthority(authorities));
    }
	public String getId() {
		return id;
	}

	@Override
	public String getUsername() {
		return username;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public String getPassword() {
		return password;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return authorities;
	}

	@Override
	public boolean isEnabled() {
		return enabled;
	}

}
